package com.hzw.code.net.json

import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter

/**
 *
 * @Author:         HuaZhongWei
 * @CreateDate:     2020/4/15 16:37
 *
 * @Description:    String类型字段适配
 *
 */
class StringAdapter : TypeAdapter<String>() {
    override fun write(out: JsonWriter?, value: String?) {
        if (value == null) {
            out?.nullValue()
            return
        }
        out?.value(value)
    }

    override fun read(jr: JsonReader?): String {
        if (jr == null) {
            return ""
        }
        if (jr.peek() == JsonToken.NULL) {
            jr.nextNull()
            return ""
        }

        val nextString = jr.nextString()
        return if (nextString == "null") {
            ""
        } else {
            nextString
        }
    }
}